package com.ruoyi.statistics.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.statistics.mapper.GoodAnalyseMapper;
import com.ruoyi.statistics.service.IGoodAnalyseService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;

/**
 * 商品数据分析Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Service
public class GoodAnalyseServiceImpl implements IGoodAnalyseService 
{
    @Autowired
    private GoodAnalyseMapper goodAnalyseMapper;

    /**
     * 获取销量趋势数据（折线图）
     */
    @Override
    public List<Map<String, Object>> getSalesTrend(Long orgId, String startDate, String endDate, String timeType)
    {
        // 设置默认时间范围（最近30天）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            endDate = DateUtils.getDate();
            startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("timeType", timeType);
        
        List<Map<String, Object>> trendData = goodAnalyseMapper.selectSalesTrend(params);
        
        // 数据处理：确保时间序列完整性
        return processTrendData(trendData, startDate, endDate, timeType);
    }

    /**
     * 获取品类结构数据（环形饼图）
     */
    @Override
    public List<Map<String, Object>> getCategoryStructure(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（最近30天）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            endDate = DateUtils.getDate();
            startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        List<Map<String, Object>> categoryData = goodAnalyseMapper.selectCategoryStructure(params);
        
        // 计算占比
        return processCategoryData(categoryData);
    }

    /**
     * 获取SKU矩阵数据（气泡图）
     */
    @Override
    public List<Map<String, Object>> getSkuMatrix(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（最近30天）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            endDate = DateUtils.getDate();
            startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        List<Map<String, Object>> matrixData = goodAnalyseMapper.selectSkuMatrix(params);
        
        // 数据处理：计算象限分类
        return processMatrixData(matrixData);
    }

    /**
     * 获取综合统计数据
     */
    @Override
    public Map<String, Object> getSummaryData(Long orgId, String startDate, String endDate)
    {
        // 设置默认时间范围（最近30天）
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            endDate = DateUtils.getDate();
            startDate = DateUtils.dateTime(DateUtils.addDays(DateUtils.getNowDate(), -30));
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        return goodAnalyseMapper.selectSummaryData(params);
    }

    /**
     * 处理趋势数据，确保时间序列完整性
     */
    private List<Map<String, Object>> processTrendData(List<Map<String, Object>> data, String startDate, String endDate, String timeType) {
        // 这里可以添加数据填充逻辑，确保时间序列的连续性
        // 对于缺失的时间点，可以填充0值
        return data;
    }

    /**
     * 处理品类数据，计算占比
     */
    private List<Map<String, Object>> processCategoryData(List<Map<String, Object>> data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        
        // 计算总销售额
        double totalAmount = data.stream()
            .mapToDouble(item -> Double.parseDouble(item.get("value").toString()))
            .sum();
        
        // 计算占比
        for (Map<String, Object> item : data) {
            double value = Double.parseDouble(item.get("value").toString());
            double percentage = totalAmount > 0 ? (value / totalAmount) * 100 : 0;
            item.put("percentage", Math.round(percentage * 100.0) / 100.0);
        }
        
        return data;
    }

    /**
     * 处理矩阵数据，计算象限分类
     */
    private List<Map<String, Object>> processMatrixData(List<Map<String, Object>> data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        
        // 计算平均值作为象限分界线
        double avgTurnover = data.stream()
            .mapToDouble(item -> Double.parseDouble(item.get("turnoverRate").toString()))
            .average().orElse(0);
        
        double avgMargin = data.stream()
            .mapToDouble(item -> Double.parseDouble(item.get("marginRate").toString()))
            .average().orElse(0);
        
        // 为每个SKU分配象限
        for (Map<String, Object> item : data) {
            double turnover = Double.parseDouble(item.get("turnoverRate").toString());
            double margin = Double.parseDouble(item.get("marginRate").toString());
            
            String quadrant;
            if (turnover >= avgTurnover && margin >= avgMargin) {
                quadrant = "明星产品";
            } else if (turnover < avgTurnover && margin >= avgMargin) {
                quadrant = "潜力产品";
            } else if (turnover >= avgTurnover && margin < avgMargin) {
                quadrant = "引流产品";
            } else {
                quadrant = "滞销产品";
            }
            
            item.put("quadrant", quadrant);
        }
        
        return data;
    }
}